import {defineStore} from 'pinia'
import {RequestData, UpdateUserData, userInfo} from "@/api/user/types.ts";
import {getAvatar, getUserList} from "@/api/user";
import {Role} from "@/api/role/type.ts";

interface avatars {
    [key: number]: string
}

export const useUsersStore = defineStore('users', () => {
    const pageSize = reactive([10, 20, 30, 50])
    const filteredData = reactive<RequestData>({
        page: 1,
        pageSize: pageSize[0],
        userName: '',
        loginName: '',
        roleName: '',
        phone: '',
        email: '',
        status: -1,
    })
    let editUserData = reactive<UpdateUserData>({
        ID: 0,
        userName: '',
        loginName: '',
        password: '',
        sex: 0,
        age: 0,
        phone: '',
        email: '',
        roles: [],
        status: 1,
    })
    const total = ref(0);
    const userList = reactive<userInfo[]>(
        []
    )
    const roleList = reactive<Role[]>([])
    const createUserDrawer = ref(false)
    const editUserDrawer = ref(false)
    const avatars = ref<avatars>({});

    // 获取用户列表
    const getUserListFun = async () => {
        try {
            const res = await getUserList(filteredData)
            if (res.code === 200) {
                userList.length = 0
                userList.push(...res.data.userList)
                roleList.length = 0
                roleList.push(...res.data.roleList)
                total.value = res.data.total
                return Promise.resolve("ok")
            } else {
                return Promise.reject(res.msg)
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 格式化头像
    async function formatAvatar(row: userInfo) {
        try {
            const response = await getAvatar(row.avatar);
            avatars.value[row.ID] = URL.createObjectURL(response);
        } catch (e) {
            avatars.value[row.ID] = '';
        }
    }

    return {
        filteredData,
        userList,
        getUserListFun,
        total,
        pageSize,
        roleList,
        createUserDrawer,
        editUserDrawer,
        editUserData,
        avatars,
        formatAvatar
    }
})
